<template>
  <div class="notice-box">
    <!-- 顶部统计 -->
    <div class="notice-header">
      <el-card shadow="never">
        <div class="summary-card">
          <div class="summary-item">
            <el-icon size="24"><Bell /></el-icon>
            <div>
              <span class="label">总通知</span>
              <span class="value">{{ total }}</span>
            </div>
          </div>
          <div class="summary-item">
            <el-icon size="24"><Message /></el-icon>
            <div>
              <span class="label">未读</span>
              <span class="value text-red-500">{{ unreadCount }}</span>
            </div>
          </div>
          <div class="summary-item">
            <el-icon size="24" class="text-green-500"><CircleCheck /></el-icon>
            <div>
              <span class="label">已读</span>
              <span class="value text-green-500">{{ readCount }}</span>
            </div>
          </div>
        </div>
      </el-card>
    </div>
    <!-- 一键标记已读 -->
    <div v-if="unreadCount > 0">
      <el-button type="primary" :loading="reading" @click="markAllAsRead">一键标记已读</el-button>
    </div>
    <!-- {{ refUnreadCountInType }}天后用完 -->
    <!-- 分类 tabs -->
    <el-tabs v-model="activeType">
      <el-tab-pane v-for="type in noticeTypes" :key="type.value" :name="type.value">
        <template #label>
          <el-badge class="ebd-item" :show-zero="false" :value="refUnreadCountInType[type.value]">
            <span> {{ type.label }}</span>
          </el-badge>
        </template>
      </el-tab-pane>
    </el-tabs>
    <!-- 通知列表 + 分页（每个 tab 独立分页）-->
    <NoticeList :type="activeType" @update-total="handleUpdateTotal" @mark-read="handleMarkRead" />
  </div>
</template>

<script setup lang="ts">
import { ref, h, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Bell, Message, CircleCheck } from '@element-plus/icons-vue';
import NoticeList from './noticeList.vue'; // 子组件路径请根据实际调整
import { BellFilled, Box, Edit } from '@element-plus/icons-vue';
import {
  getUserUnreadNoticeCountInType,
  markAllUserNoticeAsRead,
  getUserUnreadNoticeCount
} from '../../../api/system/notice';

const noticeTypes = [
  { label: '发货通知', value: '2', icon: Box },
  { label: '退货通知', value: '1', icon: BellFilled },
  { label: '签收通知', value: '3', icon: Edit },
  { label: '其他通知', value: '4', icon: Edit }
];

const activeType = ref('2');
const unreadCount = ref(0);
const total = ref(0);
const readCount = ref(0);
const reading = ref(false);

// 获取全局未读数量（用于顶部统计）
async function fetchGlobalUnreadCount() {
  try {
    const res = await getUserUnreadNoticeCount();
    if (res.code === 200) {
      total.value = res.data.total || 0;
      readCount.value = res.data.read || 0;
      unreadCount.value = res.data.unRead || 0;

      // 刷新当前分类未读数量
      fetchUnreadCountInType();
    }
  } catch (error) {
    console.error('获取未读通知失败:', error);
  }
}

// 获取当前分类未读数量（用于顶部统计）
const refUnreadCountInType = ref({
  '1': 0,
  '2': 0,
  '3': 0,
  '4': 0
});
// 获取当前分类未读数量（用于顶部统计）
async function fetchUnreadCountInType() {
  try {
    const res = await Promise.all(
      noticeTypes.map((type) => getUserUnreadNoticeCountInType({ type: type.value }))
    );
    if (res.every((item) => item.code === 200)) {
      noticeTypes.forEach((type) => {
        refUnreadCountInType.value[type.value] =
          res.find((item) => item.type === type.value)?.data.unRead || 0;
      });
    }
  } catch (error) {
    console.error('获取当前分类未读通知失败:', error);
  }
}

// 由子组件通知更新总数（因为分页后总数来自列表接口）
function handleUpdateTotal(newTotal: number, newUnreadInType: number) {
  total.value = newTotal;
  // 注意：这里 total 是当前 tab 的总数，不是全局。若要显示全局总数，应另调接口。
  // 当前设计：顶部“总通知”显示当前 tab 总数，“未读”显示全局未读（更合理）
  readCount.value = total.value - newUnreadInType;
}

// 子组件触发标记已读后，同步减少全局未读数
function handleMarkRead() {
  fetchGlobalUnreadCount();
}

// 一键标记已读
async function markAllAsRead() {
  reading.value = true;
  const res = await markAllUserNoticeAsRead();
  reading.value = false;
  if (res.code === 200) {
    ElMessage({
      message: '一键标记已读成功',
      type: 'success'
    });
    fetchGlobalUnreadCount(); // 刷新全局未读数量
  }
}

onMounted(() => {
  fetchGlobalUnreadCount(); // 只需加载一次全局未读
});
</script>

<style scoped lang="scss">
.notice-box {
  padding: 16px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.notice-header {
  margin-bottom: 16px;

  .summary-card {
    display: flex;
    justify-content: space-around;
    padding: 8px 12px;
    border-radius: 12px;

    .summary-item {
      display: flex;
      align-items: center;
      gap: 8px;
      text-align: center;

      .label {
        display: block;
        font-size: 14px;
        color: #999;
        margin-bottom: 5px;
      }
      .value {
        font-size: 22px;
        color: #454545;
        font-weight: bold;
      }
    }
  }
}
</style>
